<?php
declare(strict_types=1);

namespace ImiApp\ApiServer\Backend\Controller;

use Imi\Server\Http\Route\Annotation\Action;
use Imi\Server\Http\Route\Annotation\Controller;
use Imi\Server\Http\Route\Annotation\Route;
use Phpben\Imi\Validate\Annotation\Validate;
use Psr\Http\Message\ResponseInterface;
use Imi\Aop\Annotation\Inject;
use Phpben\Imi\Auth\Annotation\Auth;

use ImiApp\ApiServer\Backend\Controller\CommonController as CommonController;

use Imi\Db\Db;
/**
 * @Auth(name="backend")
 * @Controller("/change_coach/")
 */
class ChangeCoachController extends CommonController
{
    /**
     * @Inject("ChangeCoachService")
     */
    protected $service;

    /**
     * @Action
     * 
     * @return ResponseInterface
     */
    public function read(): ResponseInterface
    {
        return $this->response->success(null, $this->service->read() ?: []);
    }

    /**
     * @Action
     * 
     * @Validate
     * @param $data
     * @return ResponseInterface
     */
    public function create($data): ResponseInterface
    {
        return $this->service->create($data) ? $this->response->success('创建成功') : $this->response->error($this->service->getError());
    }

    /**
     * @Action
     * 
     * @Validate
     * @param $data
     * @return ResponseInterface
     */
    public function update($data): ResponseInterface
    {
        $data = $this->request->getParsedBody();
        $res = Db::name('change_coach')->where('id','=',$data['id'])->find();
        if(isset($data['status']) && $data['status']=='2'){
            if($res['status']=='1'){
                if( isset($data['new_pid']) && $data['new_pid']>0){
                    //修改辅导员
                Db::name('store')->where('id','=',$res['store_id'])->update(['pid'=>$data['new_pid']]);
                }else{
                    return  $this->response->error('没有填写新辅导员');
                }
                
           
            }
        }
        $data['updatetime'] = time();
        return $this->service->update($data) ? $this->response->success('更新成功') : $this->response->error($this->service->getError());
    }

    /**
     * @Action
     * 
     * @return ResponseInterface
     */
    public function delete(): ResponseInterface
    {
        return $this->service->delete() ? $this->response->success('删除成功') : $this->response->error($this->service->getError());
    }

    /**
     * @Action
     * 
     * @return ResponseInterface
    */
    public function operate(): ResponseInterface
    {
        return $this->service->operate() ? $this->response->success('操作成功') : $this->response->error($this->service->getError());
    }

        
}